自建通用GitHub Package npm包
初始化项目
mkdir yi-resource
cd yi-resource
pnpm init #如果报错啥yarn的, 保证上层目录没有yarn配 置即可,比如做个子目录放进去初始化,再取出来
安装 TypeScript
pnpm add -D typescript
然后初始化 tsconfig:
npx tsc --init
修改相关文件
一个 完整可用模板,支持:
-
pnpm 项目
-
TypeScript + JSON 支持
-
私有 npm 包(GitHub Packages)发布配置
-
README 包含版本管理、安装、使用说明
项目结构
yi-resource/
├─ src/
│ ├─ index.ts
│ ├─ utils.ts
│ └─ data.json
├─ package.json
├─ tsconfig.json
├─ README.md
└─ .npmrc
1️⃣ package.json
{
"name": "@your-username/yi-resource",
"version": "0.0.1",
"description": "A private utility package for JSON and TS utils",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"files": ["dist"],
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"prepare": "pnpm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/your-username/yi-resource.git"
},
"license": "MIT",
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
},
"devDependencies": {
"typescript": "^5.2.0"
}
}
⚠️ 注意:
替换
@your-username为你的 GitHub 用户名。
publishConfig.registry指向 GitHub Packages。
2️⃣ tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"moduleResolution": "node"
},
"include": ["src"]
}
3️⃣ src/utils.ts
export const add = (a: number, b: number) => a + b;
export const greet = (name: string) => `Hello, ${name}!`;
4️⃣ src/data.json
{
"name": "yi-resource",
"version": "0.0.1"
}
5️⃣ src/index.ts
import data from './data.json';
export * from './utils';
export { data };
6️⃣ .npmrc
@your-username:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN
替换
YOUR_GITHUB_TOKEN为 GitHub Personal Access Token,需要read:packages write:packages权限。
7️⃣ README.md
# yi-resource
A private utility package for JSON and TypeScript utils.
## 安装
```bash
pnpm add @your-username/yi-resource
确保你的项目 .npmrc 已配置 GitHub Packages registry:
@your-username:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN
使用示例
import { add, greet, data } from '@your-username/yi-resource';
console.log(add(1, 2)); // 3
console.log(greet('Alice')); // Hello, Alice!
console.log(data.name); // yi-resource
版本管理
使用语义 化版本:
pnpm version patch # 修复 bug
pnpm version minor # 新功能
pnpm version major # 不兼容修改
会自动生成 Git tag:
git push && git push --tags
发布
pnpm login --registry=https://npm.pkg.github.com
pnpm publish
8️⃣ 使用方法
- 修改代码 →
pnpm run build - 更新版本 →
pnpm version patch|minor|major - 提交并推送 tag →
git push && git push --tags - 发布 →
pnpm publish - 在其他项目安装 →
pnpm add @your-username/yi-resource